<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\V2\admin\model\Order;
use app\common\model\Area;
use app\common\model\Relation;
use app\common\model\User as UserModel;
use think\App;
use think\facade\Db;
use think\facade\View;
use think\response\Json;
use addons\Builder\facade\Builder;
use app\common\model\Assets;
use app\common\model\Level;
use app\common\model\Logs;
use think\exception\ValidateException;

class User extends Base
{
    //主键，默认为id
    protected string $pk = 'id';

    //验证器
    protected string $validate = 'User';

    //主模型
    protected string $model = '\app\common\model\User';

    //关联模型
    protected array $hasOne = ['level','teamLevel', 'assets', 'agent'];

//    protected array $append = ['minTeam'];

    //普通会员
    public function ordinary(): string
    {
        return $this->setTable(['delete'], ['add' => ['size' => '50%']], [['is_active', '=', 1]]);
    }

    //正式会员
    public function formal(): string
    {
        return $this->setTable([], [], [['is_active', '=', 2]]);
    }

    public function setTable($rb = [], $tb = [], $extra_map = []): string
    {
        //构建表格数据
        $table = Builder::Table()
            ->addColumn(['type' => 'checkbox', 'title' => '全选', 'fixed' => 'left'])
            ->addColumn(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addColumn(['field' => 'nickname', 'title' => '姓名', 'modify' => '2,input', 'fixed' => 'left'])
            ->addColumn(['field' => 'code', 'title' => '会员编号', 'fixed' => 'left', 'modify' => '1,input'])
            ->addColumn(['field' => 'mobile', 'title' => '手机号', 'modify' => '2,input', 'fixed' => 'left'])
            ->addColumn(['field' => 'parent_code', 'title' => '推荐人', 'modify' => '1,input'])
            ->addColumn(['field' => 'password', 'title' => '登录密码', 'placeholder' => ',默认111111', 'modify' => '1,password', 'hide' => 'true'])
            ->addColumn(['field' => 'pay_password', 'title' => '支付密码', 'placeholder' => ',默认222222', 'modify' => '1,password', 'hide' => 'true'])
            ->addColumn(['field' => 'level_id', 'title' => '会员等级', 'modify' => '4,select,getLevel','templet' => '<span>{{d.level?d.level.title:"暂无"}}</span>'])
            ->addColumn(['field' => 'team_id', 'title' => '团队等级', 'modify' => '4,select,getTeamLevel', 'templet' => '<span>{{d.teamLevel?d.teamLevel.title:"暂无"}}</span>'])
        ;
        //渲染账户
        foreach (Assets::getFields(3) as $k => $v) {
            $table->addColumn(['field' => $k, 'title' => $v, 'templet' => '<span>{{d.assets.' . $k . '}}</span>']);
        }
        return $table->addColumn(['field' => 'my_total', 'title' => '个人业绩'])
            ->addColumn(['field' => 'team_total', 'title' => '团队业绩'])
            ->addColumn(['field' => 'small_total', 'title' => '小区业绩'])
            ->addColumn(['field' => 'now_total', 'title' => '当前新增业绩'])
            ->addColumn(['field' => 'newly_total', 'title' => '新增业绩'])
            ->addColumn(['field' => 'create_time', 'title' => '注册时间', 'width' => 150])
            ->addColumn(['field' => 'active_time', 'title' => '激活时间', 'width' => 150])
            ->addColumn(['field' => 'is_lock', 'title' => '锁定登录', 'templet' => '#is_lock', 'width' => 120])
            ->addColumn(['field' => 'is_release', 'title' => '锁定释放', 'templet' => '#is_release', 'width' => 120])
            ->addColumn(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#barDemo', 'title' => '操作', 'width' => 200])
            ->addRightButtons(
                array_merge([
                    'login' => ['title' => '登录', 'event' => '_submit', 'url' => url('user/login')->build()],
//                    'agent' => ['title' => '设置代理', 'event' => '_openNewPage', 'url' => url('user/agent')->build(),'size' => '40%'],
                    'edit'  => ['size' => '50%']

                ], $rb))
            ->addTopButtons(
                array_merge($tb, [
                    'reset_1' => [
                        'title' => '重置登录密码',
                        'icon'  => 'layui-icon-password',
                        'url'   => url('user/reset', ['type' => 1])->build(),
                        'event' => '_batchSubmit'
                    ],
                    'reset_2' => [
                        'title' => '重置支付密码',
                        'icon'  => 'layui-icon-password',
                        'url'   => url('user/reset', ['type' => 2])->build(),
                        'event' => '_batchSubmit'
                    ],
                    'export'
                ]))
            ->addSwitchTool([
                ['name' => 'is_lock', 'pk' => $this->pk, 'text' => '锁定|正常'],
                ['name' => 'is_release', 'pk' => $this->pk, 'text' => '锁定|释放'],
            ])
            ->addExtraMap($extra_map)
            ->addJsUrl(['user'])
            ->addSearch([
                ['code__nickname__mobile', '会员编号/昵称/手机号', 'input,Like']
            ])
            ->fetch();

    }

    public function agent($id = '', $tpl = '', $info = '')
    {
//        dump($info);die;
        $city = Area::where('level',2)->field('id,code,city')->select()->toArray();
        $region = UserModel::where(['delete_time'=>0])->where('is_agent','>',0)->column('is_agent');

        foreach ($city as $ke=>$va){
            $city[$ke]['checked'] = 0;
            if (!empty($region) && in_array($va['code'], $region)) {
                $city[$ke]['checked'] = 1;
            }
        }
//        dump($city);die;
        View::assign('city', $city);
        View::assign('info', UserModel::find($id));
//        View::assign('first', $first);
        return View::fetch();
    }


    public function examine($id = '', $tpl = '', $info = '')
    {
        $user = UserModel::find($id);
        $dpn = Relation::where(['uid' => $id, 'algebra' => 1])->column('new_uid');
        $team = Relation::where('uid',$id)->column('new_uid');
//        $team[] = $this->user->id;
        View::assign([
            'dpn'        => count($dpn),
            'dpn_total'  => UserModel::whereIn('id', $dpn)->sum('my_total'),
            'dpn_order'  => Order::whereIn('uid', $dpn)->count(),
            'team'       => count($team),
            'team_total' => $user->team_total,
            'team_order'  => $user->team_count,
            'my_total' => $user->my_total,
            'my_order'  => $user->my_count,
        ]);
        return View::fetch();
    }

    public function agent_save(): Json
    {
        try {
            $param = $this->request->param();
            $user = UserModel::find($param['id']);
            if($user->is_agent&&$param['is_agent'])
            {
                return json(['code' => -1, 'msg' => '已是代理']);
            }
            UserModel::update(['is_agent'=>$param['is_agent']],['id'=>$param['id']]);
//            dump($param);die;
            if($param['is_agent'])
            {
                return json(['code' => 1, 'msg' => '已设为代理']);
            }else{
                return json(['code' => -1, 'msg' => '已取消']);
            }


        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($this->request->post(), $model); // TODO: Change the autogenerated stub
    }

    public static function getLevel(): array
    {
        return array_merge([0 => '暂无'], Level::column('title', 'id'));
    }

    public static function getTeamLevel(): array
    {
        return array_merge([0 => '暂无'], \app\common\model\TeamLevel::column('title', 'id'));
    }

    public function reset($type): Json
    {
        try {
            $ids = $this->request->post('ids');
            if ($type == 1) {
                $key = 'password';
                $value = md5('111111');
                $name = '登录密码';
            } else {
                $key = 'pay_password';
                $value = md5('222222');
                $name = '支付密码';
            }
            $this->model::update([$key => $value], ['id' => $ids]);
            $msg = '重置了【' . $name . '】会员标识ID【' . implode(',', $ids) . '】';
            Logs::adds($msg, $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已重置']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function relation()
    {
        try {
            if ($this->request->isAjax()) {
                $id = $this->request->param('id');
                $list = $this->model::where('parent_id', $id)->field('id,code,nickname,mobile')->select();
                foreach ($list as &$v) {
                    $level = $v->level ? $v->level->title : '暂无';
                    $v['title'] = '编号【' . $v['code'] . '】
                    姓名【' . $v->nickname . '】
                    手机号【' . $v->mobile . '】
                    等级【' . $level . '】
                  ';
                }
                return json(['code' => 1, 'msg' => 'success', 'result' => $list]);
            }
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $map['code|nickname|mobile'] = $keyword;
            } else {
                $map['code'] = 'admin';
            }
            $first = $this->model::where($map)->field('id,code,nickname,mobile')->find();
            if ($first) {
                $level = $first->level ? $first->level->title : '暂无';
                $first['title'] = '编号【' . $first->code . '】
                姓名【' . $first->nickname . '】
                手机号【' . $first->mobile . '】
                等级【' . $level . '】
               ';
            }

            View::assign('first', $first);
            return View::fetch();

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    public function login($id): Json
    {
        try {
            $user = $this->model::find($id);
            if ($user->token) {
                $token = $user->token;
            } else {
                $token = md5(time() . json_encode($user));
                $user->token = $token;
                $user->save();
            }
            cookie('token', $token);
            $description = '登录操作，会员【' . $user->code . '】';
            Logs::adds($description, $this->admin['id'], $this->admin['admin_name']);
            return json(['code' => 2, 'msg' => '登录成功', 'data' => ['code' => $user->code, 'url' => '/']]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function recharge()
    {
        $param = $this->request->param();
        if ($this->request->isAjax()) {
            switch ($param['type']) {
                case "get":
                    $user = $this->model::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')
                        ->field('id,code,mobile,nickname')->select();
                    return json(['code' => 0, 'data' => $user]);
                case "account":
                    $assets = Assets::where('uid', $param['id'])->value($param['val']);
                    if ($assets) {
                        return json(['code' => 1, 'msg' => '', 'result' => $assets]);
                    } else {
                        return json(['code' => -1, 'msg' => '加载失败']);
                    }
                case "save":
                    try {
                        $this->validate($param, 'Recharge');
                    } catch (ValidateException $e) {
                        return json(['code' => -1, 'msg' => $e->getError()]);
                    }
                    return $this->model::recharge($param, $this->admin);
                default:
                    return json(['code' => -1, 'msg' => '加载失败']);
            }
        }
        View::assign('assets', Assets::getFields(3));
        return View::fetch();
    }

    public function delete($key = 'is_del'): Json
    {

        try {
            $id = $this->request->post($this->pk);
            $user = $this->model::where('id', $id)->find();
            if (empty($user)) {
                return json(['code' => -1, 'msg' => '会员不存在']);
            }
            if ($user->is_active == 2) {
                return json(['code' => -1, 'msg' => '会员已激活，无法删除']);
            }
            $count = Relation::where('uid', $user->id)->count();
            if ($count) {
                return json(['code' => -1, 'msg' => '该会员已推荐会员无法删除']);
            }
            Relation::destroy(['new_uid' => $user->id], true);
            $this->model::destroy(['id' => $user->id], true);

            Logs::adds('删除会员【' . $user->code . '】', $this->admin->id, $this->admin->admin_name);
            return json(['code' => 1, 'msg' => '已删除']);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }


    }

}
